package com.wbsxch.blog.utils;

import com.aliyun.oss.OSSClient;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

public class OSSClientUtils {

    private final static String BASE_IMAGE_URL = "https://wbsxch.oss-cn-hangzhou.aliyuncs.com/";
    private final static String ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";
    private final static String ACCESSKEYID = "LTAISmGBvrC4Lbqa";
    private final static String ACCESSKEYSECRET = "rMUnpKRhzufpc0piBmjlmmpR8WXj8F";
    private final static String BUCKETNAME = "wbsxch";
    public final static String IMAGESURL = "images/";
    public final static String AVATARURL = "avatar/";

    private OSSClientUtils(){

    }


    private static void save(OSSClient ossClient,String objectName, InputStream inputStream){
        ossClient.putObject(BUCKETNAME, objectName, inputStream);
    }

    //私有bucket获取的图片地址
    private static String getImageUrl(OSSClient ossClient,String objectName){
        Date expiration = new Date(new Date().getTime() + 31536000000L);
        URL url = ossClient.generatePresignedUrl(BUCKETNAME, objectName, expiration);
        return url.toString();
    }

    private static void shutdown(OSSClient ossClient){
        ossClient.shutdown();
    }

    public static String uploadImage(String objectName, InputStream inputStream){
        OSSClient ossClient = new OSSClient(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        save(ossClient,objectName,inputStream);
        String imageUrl = BASE_IMAGE_URL+objectName;
        shutdown(ossClient);
        return imageUrl;
    }
}
